<template>
    <view v-if="itemDiplay" class="wy-form-select wy-flex-1" :class="[scrollClass,model.theme.box.class]" :style="model.theme.box.style">
        <template v-if="model.showBox">
            <view class="wy-form-group wy-flex-row wy-position-relative">
                <view class="wy-form-group-min-height"></view>
                <view :class="[model.theme.group.class,model.multiline?'wy-flex-column':'wy-flex-row wy-align-center']" :style="model.theme.group.style" class="wy-flex-1 wy-form-group-content">
                    <view class="wy-form-group-title wy-flex-row  wy-align-center" v-if="model.title" :class="[model.theme.titleBox.class,titleMinWidth,model.multiline?'':'wy-justify-end']" :style="model.theme.titleBox.style">
                        <text class="wy-size-base wy-color-text" :class="[model.theme.title.class]" :style="model.theme.title.style">{{locale(model.title)}}</text> 
                        <text class="wy-size-base wy-color-text" :class="[model.theme.sp.class]" v-if="model.sp">{{model.sp}}</text>
                    </view>
					<view v-if="model.multiline && model.remark" class="wy-flex-column">
						<text class="wy-size-s wy-color-second" v-for="(remark,index) in remarkArr" :key="index">{{remark}}</text>
					</view>
                    <view class="wy-flex-1 wy-flex-row wy-align-center wy-ps-tb-ss">
                        <!--按照表单默认样式的内容区-->
						<picker
						v-if="model.mode == 'select'"
						@click="click"
						:name="model.name" 
						class="wy-form-group-input wy-flex-1 wy-flex-column wy-justify-center"
						:class="[model.theme.input.class,validateClass,model.disabled?'wy-form-group-disabled':'']"
						:style="model.theme.input.style"
						:disabled="model.disabled||model.search.open"
						:range-key="rangekey"
						@change="change"
						:value="selectIndex"
						:range="selectValues"
						>
							<view class="wy-flex-row wy-flex-1 wy-ps-tb-ss wy-flex-wrap">
								<view class="wy-flex-1 wy-flex-row">
									<text class="wy-form-group-placeholder wy-size-base" v-if="showSelectPlaceholder">
										{{locale(model.placeholder)}}
									</text>
									<view class="wy-flex-1 wy-flex-row wy-flex-wrap">
										<!-- #ifdef APP-NVUE -->
										<text style="width: 1rpx;" class="wy-flex-1 wy-color-text wy-size-base wy-lines wy-lines-wrap wy-lines-1">{{activeSelectValue}}</text> 
										<!-- #endif -->
										<!-- #ifndef APP-NVUE -->
										<text style="width: 1rpx;" class="wy-flex-1 wy-color-text wy-size-base wy-lines wy-lines-wrap">{{activeSelectValue}}</text> 
										<!-- #endif -->
									</view> 
								</view>
								<wy-icon name="triangledownfill" :stop="false"></wy-icon>
							</view>
						</picker> 
                        <template v-else-if="model.mode == 'select-group'">
                        	
                        </template>
						<radio-group 
							v-else-if="model.mode == 'radio'"
							@change="bindRadioChange" class="wy-flex-1 wy-flex-column "> 
							<view class="wy-flex-1 wy-flex-column wy-form-group-input wy-ps-all-ss" 
								:class="[model.theme.input.class,validateClass,model.disabled?'wy-form-group-disabled':'']"
								:style="model.theme.input.style" 
							>
								<view class="wy-flex-1 wy-flex-row wy-flex-wrap">
									<view class="wy-flex-row wy-ms-right-s wy-ps-tb-ss" :class="check.key" :style="check.style" v-for="check in checkValues" :key="check.key">
										<radio color="#ffffff" :disabled="model.disabled" :class="[check.checked?'checked wy-primary':'wy-form-group-input-bg']"  :checked="check.checked" :value="check.value"></radio>
										<text class="wy-size-base wy-color-text" @click="setRadio(check.value)">{{check.name}}</text>
									</view> 
								</view>
								<view v-if="model.other.open" class="wy-flex-row wy-form-select-search-other  wy-align-center">
									<text class="wy-color-text wy-size-base">{{locale(model.other.title)}}</text> 
									<view class="wy-flex-1 wy-flex-row  wy-ps-lr-base">
										<input  
										class="wy-flex-1 wy-bg-inverse wy-ps-lr-ss"
										:class="[model.theme.other_input.class]"
										:style="model.theme.other_input.style"
										 v-model="model.other.value"
										:placeholder="locale(model.other.placeholder)"
										
										/>
									</view>
								</view> 
							</view> 
						</radio-group> 
                        <template v-else-if="model.mode == 'radio-group'">
                        	
                        </template>
                        <checkbox-group
                        	v-else-if="model.mode == 'checkbox'"
                        	@change="bindCheckboxChange" class="wy-flex-1 wy-flex-column wy-form-group-checkbox"> 
                        	<view class="wy-flex-1 wy-flex-column wy-form-group-input wy-ps-all-ss" 
                        		:class="[model.theme.input.class,validateClass,model.disabled?'wy-form-group-disabled':'']"
                        		:style="model.theme.input.style" 
                        	>
                        		<view class="wy-flex-1 wy-flex-row wy-flex-wrap">
                        			<view class="wy-flex-row wy-ms-right-s wy-ps-tb-ss" :class="check.key" :style="check.style" v-for="check in checkValues" :key="check.key">
                        				<checkbox :color="checkBoxColor" class="wy-form-group-checkbox-input" :disabled="model.disabled" :class="[check.checked?'checked wy-primary':'wy-form-group-input-bg']"  :checked="check.checked" :value="check.value"></checkbox>
                        				<text class="wy-size-base wy-color-text" @click="setCheck(check.value,check.checked)">{{check.name}}</text>
                        			</view> 
                        		</view>
								<view v-if="model.other.open" class="wy-flex-row wy-form-select-search-other  wy-align-center">
									<view class="wy-flex-row wy-ms-right-s wy-ps-tb-ss">
										<checkbox :color="checkBoxColor" class="wy-form-group-checkbox-input" :disabled="model.disabled" :class="[otherCheckBoxChecked?'checked wy-primary':'wy-form-group-input-bg']"  :checked="otherCheckBoxChecked" value="OTHER_CHECKBOX_VALUE"></checkbox>
										<text class="wy-size-base wy-color-text" @click="setOtherCheckBox">{{locale(model.other.title)}}</text>
									</view> 
									<view class="wy-flex-1 wy-flex-row  wy-ps-lr-ss">
										<input  
										class="wy-flex-1 wy-bg-inverse wy-ps-lr-ss"
										:class="[model.theme.other_input.class]"
										:style="model.theme.other_input.style"
										 v-model="model.other.value"
										:placeholder="locale(model.other.placeholder)"
										
										/>
									</view>
								</view> 
                        	</view> 
                        </checkbox-group>  
                        <template v-else-if="model.mode == 'checkbox-group'">
                        	
                        </template> 
                        <!----> 
                        <view @click="unitClick" v-if="showUnit||model.unit.length||model.theme.unit.class||model.theme.unit.style" :class="[model.theme.unit.class]" :style="model.theme.unit.style" class="unit wy-ms-left-ss">
                        	<slot name="unit"></slot>
                            <text class="wy-color-text wy-size-base">{{locale(model.unit)}}</text>
                        </view>
						<view v-if="showRest" :class="[model.theme.reset.class]" :style="model.theme.reset.style" class="wy-ms-left-ss">
							<slot name="reset"></slot>
						    <wy-icon @iconClicked="resetClick" name="delete" type="info"></wy-icon> 
						</view>
                        <view class="wy-ms-left-ss" v-if="model.tip">
                            <wy-icon @iconClicked="showTip" name="warn" type="error"></wy-icon> 
                        </view>
						<view class="wy-ms-left-ss" v-if="!model.multiline && model.remark">
						    <wy-icon @iconClicked="showRemark" name="question" type="error"></wy-icon>
						</view>
						
                    </view> 
                </view> 
            </view>
        </template>
        <template v-else>
            <!--自定义样式内容区-->
            <slot></slot>
             <!----> 
        </template> 
		<wy-modal ref="wyModal" type="bottom" :showAction="false" :showTitle="false" :showClose="false">
			<view class="wy-flex-row wy-form-select-search wy-ps-all-s wy-align-center" v-if="model.search.open">
				<text class="wy-size-base wy-color-second wy-ps-lr-ss" @click="hidePickerView(false)">{{locale(model.search.cancelText)}}</text>
				<view class="wy-flex-1 wy-flex-row  wy-ps-lr-base">
					<input  
					class="wy-flex-1 wy-bg-inverse wy-ps-lr-ss"
					:class="[model.theme.search_input.class]"
					:style="model.theme.search_input.style"
					 v-model="searchKeyword"
					:placeholder="locale(model.search.placeholder)"
					
					/>
				</view>
				<text class="wy-size-base wy-color-primary wy-ps-lr-ss" @click="hidePickerView(true)">{{locale(model.search.confirmText)}}</text>
			</view>
			<view class="wy-flex-column">
				<picker-view  :value="searchPickerValue" @change="searchChange"  class="wy-text-center wy-align-center wy-justify-center wy-full-width wy-form-picker-view">
				    <picker-view-column>  
				        <view class="wy-align-center wy-justify-center wy-form-picker-view-item" v-for="(item,index) in searchValues" :key="index">
				            <text class="wy-color-text wy-size-base wy-form-picker-view-item-text">{{item.name}}</text> 
				        </view>
				    </picker-view-column>
				</picker-view>
			</view> 
			<view v-if="showOtherInput" class="wy-flex-column"> 
				<view class="wy-flex-row wy-form-select-search-other wy-ps-all-s wy-align-center">
					<text class="wy-color-text wy-size-base">{{locale(model.other.title)}}</text> 
					<view class="wy-flex-1 wy-flex-row  wy-ps-lr-base">
						<input  
						class="wy-flex-1 wy-bg-inverse wy-ps-lr-ss"
						:class="[model.theme.other_input.class]"
						:style="model.theme.other_input.style"
						 v-model="model.other.value"
						:placeholder="locale(model.other.placeholder)"
						
						/>
					</view>
				</view>
			    
			</view>
		</wy-modal>
    </view>
</template>

<script>
    import {wyProps} from '../../libs/props.js';
    import {wyItem} from '../../libs/form.js'; 
	import {wy,pubfn} from '../../libs/context.js' 
	const OTHER_SELECT_INDEX = -99 //其他选择的所索引常量
	const OTHER_CHECKBOX_VALUE ='OTHER_CHECKBOX_VALUE'
    export default { 
         name:'wy-form-select', 
         mixins: [wyProps,wyItem],
         data(){
             return {
                model:{
                    theme:{
                        box:{class:'',style:''},
                        group:{class:'',style:''}, 
                        titleBox:{class:'',style:''},
                        title:{class:'',style:''},
                        input:{class:'',style:''},
                        sp:{class:'',style:''},
                        unit:{class:'',style:''},
						reset:{class:'',style:''},
						search_input:{class:'',style:''},
						other_input:{class:'',style:''},
                    },
                    /* 系统内置属性
                    //公共属性
                    uuid:'',//实例key
                    name:'',//表单key 
                    title:'',//标题
                    value:'', //值
                    tip:'',//提示语
                    tipType:'',//提示类型
                    disabled:false,//是否禁用
                    display:true,//是否展示
                    focus:false,//是否有焦点
                    multiline:false,//是否分行
                    //公共事件
                    checkCommit:null,//提交前置条件检查
                    showTip:null,//弹出提示信息
                    callback:null,  //set事件监听 
                    //事件
                    events:{
                        click:null,
                        unitClick:null,
                        input:null
                    }, 
                    //国际化
                    locale:{ //本地化
                    	group:'',
                        file:'',
                    	isContent:true,
                    	open:false
                    },
                    //辅助
                    sp:'',// :标题与值之间分隔符，
                    width:0,//标题最大宽度，0代表自动判断
                    unit:'',//单位
                    placeholder:'',// 
                    */
                    //自定义属性 
					showContent:true,
                    showBox:true ,//是否显示内容区 
					mode:'select' ,//模式select select-group radio radio-group checkbox checkbox-group 
					rangekey:'name',//通过 range-key 来指定 Object 中 key 的值作为选择器显示内容
					valuekey:'value',// Object 中 key 的值作为选择器选择的值
					groupkey:'group',//Object作为分组的key
					group:undefined,//值过滤器 默认过滤group值
					values:[],//值
					valuesLocale:false, //值国际化
					rangkeyLocale:{ //键国际化
						key:'',
						isContent:false,
						group:''
					},
					//开启值其它选项
					other:{
						open:false, 
						title:'其它', 
						rangekey:'', 
						sp:'',//分隔符
						value:'',
						placeholder:'输入其它值'
					},
					//开启搜索
					search:{
						open:true, 
						placeholder:'输入关键字',
						cancelText:'取消',
						confirmText:'确定',
						keyword:'',
						lodash:300,
						event:null
					},
					//checkbox
					valueSp:',',//多选值分隔符
					showReset:false,//是否展示重置按钮
					//resetValue:'',//重置值 
                },
				selectIndex:-1,//当前选择的项目索引
				searchIndex:-1,
				searchKeyword:'',
				searchValues:[],
				searchPickerValue:[0],
				showOtherInput:false,
				otherCheckBoxChecked:false,
				isOtherInit:false
            }
        },
		watch:{
			searchKeyword(val){
				wy.lodash('wy-form-select-search').debounceEnd(()=>{
					this.search(val)
				},this.model.search.lodash) 
			}
		},
        computed:{
            checkBoxColor(){
              // #ifdef APP-NVUE
              return ''
              // #endif
              return '#ffffff'
            },
             //itemDiplay 组件是否隐藏
             //titleMinWidth //自动计算出来的标题宽度
             //validateClass //触发验证的样式类
			showRest(){
			 	return this.model.showReset
			},
			showSelectPlaceholder(){
				return this.selectIndex<0 &&this.selectIndex !=OTHER_SELECT_INDEX
			},
			rangekey(){
				let {rangkeyLocale,rangekey}=this.model
				if(rangkeyLocale&&rangkeyLocale.key){
					let {key,isContent,group}=rangkeyLocale
					rangekey=wy.locale(key,isContent,group)
				}
				return rangekey
			},
			selectValues(){
				let list=[]
				let {values,valuekey,mode,valuesLocale,groupkey,group}=this.model 
				if(mode!='select'){
					return list
				}
				var rangekey=this.rangekey 
				if(pubfn.isArray(values)){
					for(let i=0;i<values.length;i++){
						let val=values[i]
						if(pubfn.isObject(val)){
							let model={
								[rangekey]:'',
								[valuekey]:'',
								[groupkey]:'',
								...val
							}
							if(model[rangekey]!=''){
								var groupVal=model[groupkey]
								if(group==undefined || groupVal==group){
									list.push({
										[rangekey]:valuesLocale?this.locale(model[rangekey]):model[rangekey] ,
										[valuekey]:model[valuekey],
										[groupkey]:groupVal
									})
								}
							}
						}
						else if(pubfn.isString(val)){
							list.push({
								[rangekey]:valuesLocale?this.locale(val):val ,
								[valuekey]:val,
								[groupkey]:''
							})
						}
					}
				}
				return list
			},
			activeSelectValue(){
				let values=this.selectValues
				var selectIndex=this.selectIndex
				let {valuesLocale}=this.model
				var rangekey=this.rangekey
				if(selectIndex>=0&&values.length>selectIndex){
					return  valuesLocale?this.locale(values[selectIndex][rangekey]):values[selectIndex][rangekey]
				}
				return (this.model.other.open && selectIndex == OTHER_SELECT_INDEX) ?(valuesLocale?this.locale(this.model.other.value):this.model.other.value):''
			},
			checkValues(){
				let list=[]
				let {values,valuekey,value,valueSp,mode,valuesLocale,group,groupkey}=this.model
				if(mode=='select'){
					return list
				}
				var rangekey=this.rangekey
				if(value===null){
					value=''
				}
				var checkedList=value.toString().split(valueSp)
				if(pubfn.isArray(values)){
					for(let i=0;i<values.length;i++){
						let val=values[i]
						var checked=false
						if(pubfn.isObject(val)){
							let model={
								[rangekey]:'',
								[valuekey]:'',
								[groupkey]:'',
								style:'',
								...val
							}
							if(checkedList.indexOf(model[valuekey])>=0){
								checked=true
							}
							if(model[rangekey]!=''){
								var groupVal=model[groupkey]
								if(group==undefined || groupVal==group){
									list.push({
										name:valuesLocale?this.locale(model[rangekey]):model[rangekey] ,
										value:model[valuekey],
										group:groupVal,
										key:'checkBox_'+i,
										style:model.style,
										checked
									})
								}
							}
						}
						else if(pubfn.isString(val)){
							if(checkedList.indexOf(val)>=0){
								checked=true
							}
							list.push({
								name:valuesLocale?this.locale(val): val,
								value:val,
								group:'',
								key:'checkBox_'+i,
								style:'',
								checked
							})
						}
					}
				} 
				return list
			}  
        }, 
        methods:{ 
			setOtherCheckBox(){ 
				let {disabled,valueSp,value}=this.model
				if(disabled){
					return
				} 
				this.isOtherInit=true
				this.otherCheckBoxChecked=!this.otherCheckBoxChecked
				var _value =value.split(valueSp)
				if(value==''){
					_value=[]
				}
				var index = _value.findIndex((ee)=>{
					return ee == OTHER_CHECKBOX_VALUE
				})
				if(index>=0){
					if(!this.otherCheckBoxChecked){
						_value.splice(index,1)
					}
					//this.otherCheckBoxChecked=true 
				}
				else{
					if(this.otherCheckBoxChecked){
						_value.push(OTHER_CHECKBOX_VALUE)
					}
				}
				this.setValue(_value.join(valueSp))	
				
			},
			hidePickerView(isSelect=true){
				this.$refs.wyModal.hide()
				if(isSelect ){
					var searchIndex=this.searchIndex>=0?this.searchIndex:0
					if(searchIndex<this.searchValues.length){
						let {index}=this.searchValues[searchIndex]
						let values=this.selectValues
						let {valuekey}=this.model
						if(index>=0&&index<values.length){
							this.selectIndex=index
							let value=values[index][valuekey] 
							this.setValue(value)
						}
						else if(this.model.other.open){
							//其它值
							this.setValue(this.model.other.value)
							this.selectIndex=index
						}
					} 
					this.searchPickerValue=[searchIndex]
				}
			},
			searchChange(e){
				let index=-1
				if(e.detail.value.length>0){
					index=e.detail.value[0]
				}
				if(index>=0 && index<this.searchValues.length){
					if(this.searchValues[index].index==OTHER_SELECT_INDEX){
						this.showOtherInput=true
					}
					else{
						this.showOtherInput=false	
					}
				} 
				this.searchIndex=index
			},
			search(keyword){ 
				var that=this
				let {mode,rangekey,valuesLocale} = this.model
				keyword=keyword.trim() 
				let values=this.selectValues 
				if(mode == 'select'){
					let {event} = this.model.search
					new Promise((a)=>{
						if(event){
							if(pubfn.isFunction(event)){
								event({keyword,values}).then((list)=>{
									var nList=[]
									if(list){ 
									    for(var i=0;i<list.length;i++){
											let {index}=list
											if(index === undefined){
												index=i
											}
											nList.push({
												...list[i],
												index
											})
										}
									}
									a(nList)
								})
							} 
						}
						else{
							let itemArr=[]
							for(let i=0;i<values.length;i++){
								let val=values[i][rangekey]
								if(keyword.length==0 || val.indexOf(keyword)>=0){
									let model={
										index:i,
										name:val
									}
									itemArr.push(model)
								}
							} 
							a(itemArr)
						}
					}).then((list)=>{
						let {open,title}=this.model.other
						if(open){
							list.push({
								index:OTHER_SELECT_INDEX,
								name:valuesLocale?this.locale(title):title
							})
							if(this.selectIndex == OTHER_SELECT_INDEX){
								this.searchPickerValue=[list.length-1] 
								this.showOtherInput=true
								this.searchIndex=index=list.length-1
							}
						}
						if(this.selectIndex>=0){
							var index=list.findIndex((ee)=>{
								return ee.index == this.selectIndex
							})
							if(index>=0){
								this.searchPickerValue=[index] 
								this.searchIndex=index
							} 
						}
						that.searchValues=list
					})	
				} 
			},
            //mounted事件
            mounted__(){
               // console.log(this.model)
			   //console.log(this.selectValues)   
            },
			//首次加载完成，需要手动设置默认值
			init__(){
				this._init_select() 
			},
            //locale(key) 国际化方法
            //来自父节点的状态通知
            parentNotice__(e){
                
            },
            //外部设置model事件
            setModel__(model){
                let {group,values,value}=model
				let {mode} = this.model 
				if(values!=undefined ||group!=undefined){
					this._init_select()
				}
				if(group!=undefined){
					if(value==undefined && this.selectIndex==-1){ 
					 	this.resetClick()
					}
				}
            },
            //获取值
            getValue__(){
                let {value,mode,valueSp}=this.model
				if(mode == 'checkbox'){
					var checkedList=value.toString().split(valueSp)
					var index=checkedList.findIndex((e)=>{
						return e == OTHER_CHECKBOX_VALUE
					})
					if(index>=0){
						if(this.model.other.value==''){
							checkedList.splice(index,1)
						}
						else{
							checkedList[index] = this.model.other.value
						}
						value = checkedList.join(valueSp)
					}
				}
                return value
            },
			click__(e){
				if(this.model.search.open){
					this.search(this.searchKeyword)
					this.$refs.wyModal.show()
				}
			},
			//选择初始化
			_init_select(option={}){ 
				let {source}=option
				let {mode,value,valuekey,values,valueSp} = this.model
			    let {open}=this.model.other
				if(mode == 'select'){ 
					var selectIndex = this.selectValues.findIndex((e)=>{
						return e[valuekey] == value
					}) 
					if(value!='' && values && values.length>0){
						if(!this.isOtherInit ||source){
							this.isOtherInit=true
							if(selectIndex<0 && open && (this.model.other.value==''||source)){
								selectIndex = OTHER_SELECT_INDEX
								this.model.other.value=value
							}
						} 
						
					}
					this.selectIndex = selectIndex
				}
				else if(mode == 'checkbox'){
					if(value!='' && values && values.length>0){ 
						if(!this.isOtherInit||source){
							this.isOtherInit=true
							if(open){
								var checkedList=value.toString().split(valueSp)
								var otherVal=[]
								var checkValues=this.checkValues
								checkedList.forEach((val)=>{
									var index=checkValues.findIndex((ee)=>{
										return ee.value == val
									})
									if(index<0){
										otherVal.push(val)
									}
								})
								if(otherVal.length>0){
									this.model.other.value = otherVal.join(valueSp)
									this.otherCheckBoxChecked=true
								}
							} 
						}
						
					}
				}
			},
            //设置值
            setValue__(value,option={}){
               this._init_select(option) 
            },
            //提交前的同步验证
            async checkCommit(option,parent=null,group=''){
            	return new Promise((resolve, reject)=>{
            		resolve({error:[],group})
            	})
            }, 
			change(e){
				let index=e.detail.value
				if(isNaN(index)){
					index=0
				}
				let values=this.selectValues
				let {valuekey}=this.model
				if(index<values.length){
					this.selectIndex=index
					let value=values[index][valuekey] 
					this.setValue(value)
				}
			},
			bindRadioChange(e){
				let value = e.detail.value;
				let {disabled}=this.model
				if(disabled){
					return
				} 
				this.setValue(value)	
			},
			setRadio(val){
				let {disabled}=this.model
				if(disabled){
					return
				} 
				this.setValue(val)
			},
            bindCheckboxChange(e){ 
                let value = e.detail.value;
                let {disabled,valueSp}=this.model
                if(disabled){
                	return
                } 
                value =value?value:[]
				var index = value.findIndex((ee)=>{
					return ee == OTHER_CHECKBOX_VALUE
				})
				if(index>=0){
					this.otherCheckBoxChecked=true 
				}
				else{
					this.otherCheckBoxChecked=false
				}
                this.setValue(value.join(valueSp))	
            },
			setCheck(val,checked){
				let {value,valueSp,disabled}=this.model
				if(disabled){
					return
				} 
				var checkedList=value?value.split(valueSp):[]
				if(checked){
					//反选
					var index=checkedList.findIndex((e)=>{
						return e==val
					})
					if(index>=0){
						checkedList.splice(index, 1)
					}
				}
				else {
					//选择
					checkedList.push(val)
				} 
				this.setValue(checkedList.join(valueSp))
			},
            resetClick(){
            	let {resetValue}=this.model
				if(resetValue==undefined){
					resetValue=''
				}
            	this.setValue(resetValue,{source:'form'})
            }  
         }
        
    }
</script>

<style>
</style>
